<!DOCTYPE html>
<meta charset="utf-8">
<link rel="author" title="Mason Freed" href="mailto:masonfreed@chromium.org">
<link rel=help href="https://github.com/MicrosoftEdge/MSEdgeExplainers/blob/main/Popup/explainer.md">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>

<popup id=p1 anchor=b1><p>This is popup #1</p>
  <button id=b2 onclick='p2.show()'>Popup 2</button>
  <button id=b4 onclick='p4.show()'>Popup 4</button>
</popup>
<popup id=p2 anchor=b2><p>This is popup #2</p>
  <button id=b3 onclick='p3.show()'>Popup 3</button>
</popup>
<popup id=p3 anchor=b3><p>This is popup #3</p></popup>
<popup id=p4 anchor=b4><p>This is popup #4</p></popup>
<button id=b1 onclick='p1.show()'>Popup 1</button>

<dialog id=d1>This is a dialog<button onclick='this.parentElement.close()'>Close</button></dialog>
<button id=b5 onclick='d1.show()'>Dialog</button>

<script>
  const popups = [p1, p2, p3, p4];

  function assertState(...states) {
    assert_equals(popups.length,states.length);
    for(let i=0;i<popups.length;++i) {
      assert_equals(popups[i].open,states[i],`Popup #${i+1} incorrect state`);
    }
  }
  test(function() {
    assertState(false,false,false,false);
    p1.show();
    assertState(true,false,false,false);
    p2.show();
    assertState(true,true,false,false);
    p3.show();
    assertState(true,true,true,false);
    // P4 is a sibling of P2, so showing it should
    // close P2 and P3.
    p4.show();
    assertState(true,false,false,true);
    // P2 should close P4 now.
    p2.show();
    assertState(true,true,false,false);
    // Hiding P1 should hide all.
    p1.hide();
    assertState(false,false,false,false);
  }, "popup stacking behavior")

  test(function() {
    function openManyPopups() {
      p1.show();
      p2.show();
      p3.show();
      assertState(true,true,true,false);
    }
    openManyPopups();
    d1.show(); // Dialog.show() should hide all popups.
    assertState(false,false,false,false);
    d1.close();
    openManyPopups();
    d1.showModal(); // Dialog.showModal() should also hide all popups.
    assertState(false,false,false,false);
    d1.close();
  }, "popups should be closed by dialogs")

  test(function() {
    d1.show();
    assert_true(d1.open);
    p1.show();
    assertState(true,false,false,false);
    assert_true(d1.open);
    p1.hide();
    assert_true(d1.open);
    d1.close();
  }, "dialogs should not be closed by popups")
</script>

<style>
  #p1 { top:350px; }
  #p2 { top:350px; left:200px; }
  #p3 { top:500px; }
  #p4 { top:500px;left:200px; }
</style>
